package com.linjacy.httpproject.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class JwtUtil {
    /**
     * token私钥，不可以暴露
     */
    public static final String TOKEN_SECRET_KEY = "tokenSecretKey";
    /**
     * token过期时间（分钟）
     */
    public static final int EXPIRE_TIME = 3600;

    private static final String TOKEN_HEADER = "token";

    public static final String REDIS_TOKEN = "_token";

    /**
     * 创建token
     *
     * @param userId   用户ID
     * @param userName 用户名
     * @return token
     */
    public static String createToken(String userId, String userName) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, EXPIRE_TIME);
        return JWT.create()
                //签发对象
                .withAudience(userId)
                //载荷
                .withClaim("userName", userName)
                //签发时间
                .withIssuedAt(new Date())
                //有效时间
                .withExpiresAt(calendar.getTime())
                //加密
                .sign(Algorithm.HMAC256(TOKEN_SECRET_KEY));
    }

    /**
     * 验证token合法性
     *
     * @param token token
     * @return token是否合法
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(TOKEN_SECRET_KEY)).build().verify(token);
    }

    /**
     * 通过token获取userId
     *
     * @return userId
     */
    public static String getUserIdByToken(HttpServletRequest request) {
        String userId = null;
        String token = request.getHeader(TOKEN_HEADER);
        DecodedJWT decode = JWT.decode(token);
        List<String> audience = decode.getAudience();
        if(audience != null && audience.size() > 0){
            userId  = audience.get(0);
        }
        return userId;
    }
}
